#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;

use Logs;
use FindBin qw( $RealBin );
use MIME::Base64;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象

    # projectid addr ticketid rely name(版本信息可能为空) temp(logs目录下的临时目录名) uuid

=cut

return sub
{
    my %param = @_;

    my ( $db, $logs, $projectid, $addr, $ticketid, $rely, $name, $temp, $uuid )
        = @param{qw(db logs projectid addr ticketid rely name temp uuid )};

    $logs = Logs->new( 'code.build.dump.pull.svn' ) unless $logs;

    my ( $username, $pass );

    if( $ticketid )
    {
        my $x = eval{ $db->query( "select ticket from ticket where id='$ticketid' and type='UsernamePassword'" )};  
        $logs->die( "get data from ticket fail:$@" ) if $@;
        ( $username, $pass ) = split /_:separator:_/, $x->[0][0] if @$x;
    }

    #TODO
    #my $ctrl = $pass ? "svn --username '$username'  --password '" . decode_base64( $pass ) . "'" : 'svn';
    my $ctrl = $pass ? "svn --username '$username'  --password '" . $pass . "'" : 'svn';

    my $temppath = "$RealBin/../logs/$temp/$uuid";
    if( -d $temppath )
    {
        my $user = `id -un`;chop $user;
        my $sudo = $user eq 'root' ? '' : 'sudo ';
        $logs->die( "clean old temppath fail:$!" ) if system "${sudo}rm -rf '$temppath'";
    }

    $logs->die( "mkdir temppath fail:$!" ) if system "mkdir -p '$temppath'";



    if( $name )
    {
        $logs->die( "name format error" ) unless $name =~ /^[a-zA-Z0-9\.\-_]+$/;
        $logs->die( "clone error: $!" ) 
            if system "cd '$temppath' && rm -rf data '$name' info && $ctrl checkout '$addr/tags/$name' && mkdir -p info && mv '$name/.svn' info/ && mv '$name' data && echo '$name' > info/version";
    }
    else
    {
        $logs->die( "clone error: $!" ) 
            if system "cd '$temppath' && rm -rf data trunk info && $ctrl checkout '$addr/trunk' && mkdir -p info && mv 'trunk/.svn' info/ && mv 'trunk' data && echo release > info/version";
    }


    my $info = `cd '$temppath/info' && $ctrl log|grep ^r 2>/dev/null|head -n 1`;
    my @info = split /\s+\|\s+/, $info;
    my $tagger = $info[1];

    $logs->die( "tagger format error" ) unless defined $tagger && $tagger =~ /^[a-zA-Z0-9\.\@\-_]+$/;
    $logs->die( "write tagger info fail:$!" )if system "echo '$tagger' > '$temppath/info/tagger'";

}


